﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Text;
using System.Threading.Tasks;

namespace SimpleActor
{
    // internal helper class

    internal static class TaskHelper
    {
        public static void Connect<T>(this TaskCompletionSource<T> source, Task<T> task)
        {
            task.ContinueWith(t => source.TrySetResult(t.Result),       TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
            task.ContinueWith(t => source.TrySetException(t.Exception), TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
            task.ContinueWith(t => source.TrySetCanceled(),             TaskContinuationOptions.OnlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously);
        }

        public static void Connect(this TaskCompletionSource<Unit> source, Task task)
        {
            task.ContinueWith(t => source.TrySetResult(Unit.Default),   TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
            task.ContinueWith(t => source.TrySetException(t.Exception), TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
            task.ContinueWith(t => source.TrySetCanceled(),             TaskContinuationOptions.OnlyOnCanceled | TaskContinuationOptions.ExecuteSynchronously);
        }
    }
}
